#include <iostream>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

#define NUM 1024

void Write(int fdw)
{
    // 构建发送字符串
    char buffer[NUM];
    buffer[0] = 0;

    string s = "I am child";
    int num = 1;
    pid_t pid = getpid();

    while(1)
    {
        snprintf(buffer, sizeof(buffer), "%d - %s -mypid = %d\n", num++, s.c_str(), pid);
        //cout << buffer << endl;
        write(fdw, buffer, strlen(buffer));
        cout << "写入成功" << num++ << endl;
        //sleep(1);
        //sleep(50);  // 读写端正常， 缓冲区为空， 读取端阻塞
    }
}

void Read(int fdr)
{
    char buffer[NUM];
    buffer[0] = '\0';

    while(1)
    {
        sleep(5); // 读写端正常， 缓冲区写满， 写入端阻塞
        int n = read(fdr, buffer, sizeof(buffer));
        buffer[n] = '\0';
        pid_t pid = getpid();
        cout << "I am parent, mypid = " << pid << " , i read a message :" << buffer << endl; 
    }

}

int main()
{
    int pipefd[2] = { 0 };
    int n = pipe(pipefd);

    if(n == -1)
    {
        cout << "pipe 失败" << endl;
        return 1;
    }

    pid_t pid = fork();

    // child 写  parent 读  
    if(pid > 0)
    {
        //child
        close(pipefd[0]);

        Write(pipefd[1]);

    }
    else if(pid == 0)
    {
        //parent
        close(pipefd[1]);

        Read(pipefd[0]);

        int statue = 0; 
        int p = waitpid(pid, &statue, 0);
        if(p == -1)
        {
            cout << "waitpid 失败" << endl;
            return 1;
        }

    }
    if(pid < 0)
    {
        cout << "fork 失败" << endl;
        return 1;
    }
    

    return 0;
}